package org.spring.springboot.app.user.sysuser.controller;

import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.PageInfo;

import org.apache.commons.lang3.StringUtils;
import org.spring.springboot.app.base.R;
import org.spring.springboot.app.base.Type;
import org.spring.springboot.app.base.User;
import org.spring.springboot.app.user.sysuser.domain.po.SysUserPO;
import org.spring.springboot.app.user.sysuser.domain.vo.*;
import org.spring.springboot.app.user.sysuser.service.ISysUserService;
import org.spring.springboot.component.annotation.AccessTokenVerify;
import org.spring.springboot.util.ApiIndex;
import org.spring.springboot.util.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Api(description="用户操作接口",tags = ApiIndex.SysUserController)
@RequestMapping(value = "/api/sysUser")
@RestController
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisUtils redisUtils;

    //@AccessTokenVerify(type = AccessTokenVerifyType.TOKEN)
    @ApiOperation(value="查询用户信息列表")
    @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "String", required = true)
    @AccessTokenVerify
    @RequestMapping(value = "", method = RequestMethod.GET)
    public  R<PageInfo<List<UserQueryResVO>>> findAll(
                        @ApiIgnore User user,
                        @ApiParam(value = "登录名", required = false) @RequestParam(defaultValue = "") String loginName,
                        @ApiParam(value = "名称", required = false) @RequestParam(defaultValue = "") String name,
                        @ApiParam(value = "编号", required = false) @RequestParam(defaultValue = "") String no,
                        @ApiParam(value = "代理商ID", required = false) @RequestParam(defaultValue = "") String officeId,
                        @ApiParam(value = "排序字段(需要与数据库字段对应)", required = false) @RequestParam(defaultValue = "") String sortField,
                        @ApiParam(value = "排序方式（ascend正序,descend倒序）", required = false) @RequestParam(defaultValue = "") String sortOrder,
                        @ApiParam(value = "开始创建时间（例如1993-08-11 或者 1993-08-11 00:00:00）", required = false) @RequestParam(defaultValue = "") String startCreateDate,
                        @ApiParam(value = "结束创建时间（例如1993-08-11 或者 1993-08-11 23:59:59）", required = false) @RequestParam(defaultValue = "") String endCreateDate,
                        @ApiParam(value = "页数", required = true) @RequestParam(defaultValue = "1") int pageNum,
                        @ApiParam(value = "每页条数", required = true) @RequestParam(defaultValue = "10") int pageSize){
        UserSearchVo vo = new UserSearchVo();
        vo.setLoginName(loginName);
        vo.setName(name);
        vo.setNo(no);
        if(StringUtils.isNotBlank(startCreateDate)){
            if(startCreateDate.indexOf(":")==-1){
                startCreateDate=startCreateDate+" 00:00:00";
            }
        }
        if(StringUtils.isNotBlank(endCreateDate)){
            if(endCreateDate.indexOf(":")==-1){
                endCreateDate=endCreateDate+" 23:59:59";
            }
        }
        //if(StringUtils.isBlank(officeId)){
        //    officeId=user.getOfficeId();
        //}
        vo.setOfficeId(officeId);
        vo.setStartCreateDate(startCreateDate);
        vo.setEndCreateDate(endCreateDate);
        vo.setPageNum(pageNum);
        vo.setPageSize(pageSize);
        vo.setSortFild(sortField);
        vo.setSortOrder(sortOrder);
        R<PageInfo<List<UserQueryResVO>>> result = new R();
        List<SysUserPO> _list = sysUserService.findAll(vo);
        PageInfo p = new PageInfo(_list);
        p.setList(getSysUserVOS(p.getList()));
        result.setData(p);
        return result;
    }
    private List<UserQueryResVO> getSysUserVOS(List<SysUserPO> _list) {
        List<UserQueryResVO> list = new ArrayList<UserQueryResVO>();
        if (_list != null && _list.size()>0) {
            for (SysUserPO po : _list) {
                UserQueryResVO vo = new UserQueryResVO();
                BeanUtils.copyProperties(po,vo);
                vo.setCreate_date(vo.getCreateDate());
                list.add(vo);
            }
        }
        return list;
    }


    @ApiOperation(value="根据用户ID得到用户信息")
    @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "String", required = true)
    @AccessTokenVerify
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    // @Cacheable(value="user")//用redis缓存方法返回结果,默认10秒钟
    public R<UserQueryResVO> find(@ApiParam(value = "用户Id") @RequestParam(defaultValue = "") String id) {
        R<UserQueryResVO> r = new R<UserQueryResVO>();
        SysUserPO po = new SysUserPO();
        if(id.equals("user")){
            id = po.getUser().getId();
        }
        po = sysUserService.find(id);
        UserQueryResVO vo = new UserQueryResVO();
        BeanUtils.copyProperties(po,vo);
        r.setData(vo);
        return r;
    }

    @ApiOperation(value="得到目标在表中存在的个数")
    @RequestMapping(value = "/getUserTargetCount", method = RequestMethod.GET)
    public R<UserCheckVo> getUserTargetCount(@ApiParam(value = "需要查看的目标字段（与数据库字段对应默认为login_name）") @RequestParam(defaultValue = "login_name") String target,
                                             @ApiParam(value = "需要查看目标个数的值") @RequestParam(defaultValue = "") String value) {
        R result = new R();
        UserCheckVo vo=new UserCheckVo();
        vo.setTarget(target);
        vo.setValue(value);
        vo.setCount(sysUserService.getUserTargetCount(vo));
        result.setData(vo);
        return result;
    }
    /**
     * 添加
     */
    @ApiOperation(value="添加用户信息")
    @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "String", required = true)
    @AccessTokenVerify
    @RequestMapping(value = "", method = RequestMethod.POST)
    public R<SysUserAddResVO> save(
            @ApiParam(value = "用户对象", required = true)@RequestBody SysUserAddVO vo,
            BindingResult bindingResult
        ) {
        R result = new R();
        if (bindingResult.hasErrors()) {
            result.setCode(1);
            result.setMessage(bindingResult.getAllErrors().get(0).toString());
            result.setMessages(bindingResult.getAllErrors());
            return result;
        }
        return sysUserService.insertUserInfo(vo);
    }

    /**
     * 修改
     */
    @ApiOperation(value="修改用户信息")
    @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "String", required = true)
    @AccessTokenVerify
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public R update(@ApiParam(value = "用户对象", required = true) @RequestBody SysUserAddVO vo) {
        R result = new R();
        int code = sysUserService.update(vo);
        if (code == 0) {
            result.setCode(1);
            result.setMessage("修改失败");
        }
        if(code == 105){
            result.setType(Type.ParamValidateFail);
        }
        return result;
    }


    /**
     * 重置用户密码
     */
    @ApiOperation(value="重置用户密码")
    @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "String", required = true)
    @AccessTokenVerify
    @RequestMapping(value = "/resetPassword", method = RequestMethod.PUT)
    public R resetPassword(@ApiParam(value = "用户ID", required = true) @RequestParam("id") String id) {
        R result = new R();
        int code = sysUserService.resetPassword(id);
        if (code == 0) {
            result.setCode(1);
            result.setMessage("修改失败");
        }

        return result;
    }

    /**
     * 修改用户密码
     */
    @ApiOperation(value="修改用户密码")
    @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "String", required = true)
    @AccessTokenVerify
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.PUT)
    public R modifyPassword(@ApiIgnore User user,@RequestBody UserPasswordVO vo) {
        R result = new R();
        if(!result.valid(vo)){
            return result;
        }
        SysUserPO po = sysUserService.find(user.getId());
        if(!po.getPassword().equals(vo.getPassword())){
            return result.setType(Type.ParamValidateFail).setMessage("原密码不正确");
        }
        sysUserService.setPassword(user.getId(), vo.getNewPassword());
        return result;
    }

    /**
     * 删除
     * @param id
     */
    @ApiOperation(value="删除用户信息")
    @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "String", required = true)
    @AccessTokenVerify
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public R delete(@ApiParam(value = "用户Id", required = true) @PathVariable("id") String id) {
        R result = new R();
        int code = sysUserService.delete(id);
        if (code == 0) {
            result.setCode(1);
            result.setMessage("刪除失败");
        }
        return result;
    }


    /**
     *  批量删除
     * @param ids
     */
    @ApiOperation(value="批量删除用户信息")
    @ApiImplicitParam(name = "token", value = "token", paramType = "query", dataType = "String", required = true)
    @AccessTokenVerify
    @RequestMapping(value = "/deletes", method = RequestMethod.DELETE)
    public R deletes(@ApiParam(value = "用户ids(用,分割)", required = true) @RequestParam("ids") String ids) {
        R result = new R();
        int code = sysUserService.deletes(ids);
        if (code == 0) {
            result.setCode(1);
            result.setMessage("刪除失败");
        }
        return result;
    }



    @ApiOperation(value="查询用户角色")
    @RequestMapping(value = "/queryUserRoles", method = RequestMethod.GET)
    public R<List<UserRoleQueryVO>> queryUserRoles(
            @ApiParam(value = "用户id", required = true) @RequestParam("id") String id
    ) {
        R r = new R();
        List<UserRoleQueryVO> list = sysUserService.queryUserRoles(id);
        r.setData(list);
        return r;
    }

}
